var SM = SM || {}
SM.Panel = function(){
    var defaultConfig = {
        width: "400px",
        fixedcenter: true,
        constraintoviewport: true,
        close: true,
        visible: false,
        draggable: true,
        modal: true,
        underlay: "matte"
    }

    var createPanel = function(id, config){
        if(!config){
            config = defaultConfig;
        }else{
            config = YAHOO.lang.merge(defaultConfig, config);
        }

        return new YAHOO.widget.Panel(id, config);
    }

    return{
        createPanel:createPanel
    }
}();

SM.Transaction = function(){
    var callbacks=[], result;

    var registerCallback = function(fn){
        callbacks.push(fn);
    }

    var executeCallbacks = function(){
        for(var i=0; i < callbacks.length; i++){
            if(YAHOO.lang.isFunction(callbacks[i])){
                callbacks[i](result);
            }
        }
    }

    var responseSuccess = function(o){
        try{
            result = YAHOO.lang.JSON.parse(o.responseText);
            executeCallbacks();
            callbacks=[]; // empty callbacks array after executing function calls
        }catch(e){
            alert("error: " + e.message + "\nfile: " + e.fileName + "\nln: " + e.lineNumber);
        }
    }

    var responseFailure = function(o){
        try{
            alert("error: " + o.statusText);
        }catch(e){
            alert("error: " + e.message + "\nfile: " + e.fileName + "\nln: " + e.lineNumber);
        }
    }

    var callback = {
        success:responseSuccess,
        failure:responseFailure
    }
    
    var doPost = function(uri, postData){
        var transaction = YAHOO.util.Connect.asyncRequest('POST', uri, callback, postData);
    }

    return {
        doPost:doPost,
        registerCallback:registerCallback
    }
}();

SM.AddDomainPanel = function(){
    var panel, btnAdd, txtDomain, callbacks=[], btnCancel;
    var sUrl = "/index.php/rs/addDomain";

    var registerCallback = function(fn){
        callbacks.push(fn);
    }

    var executeCallbacks = function(result){
        for(var i=0; i < callbacks.length; i++){
            if(YAHOO.lang.isFunction(callbacks[i])){
                callbacks[i](result);
            }
        }
    }

    var addDomainTransaction = function(result){
        if(result.feedback == "invalid data"){
            alert("Invalid Entry. Please try again.");
        }else{
            panel.hide();
            alert("You have successfully added a domain.");
            executeCallbacks(result);
        }
    }

    var addDomain = function(event){
        var postQueryString = "domain=" + YAHOO.lang.trim(txtDomain.value);
        SM.Transaction.registerCallback(addDomainTransaction);
        SM.Transaction.doPost(sUrl, postQueryString);
    }

    var setVars = function(){
        btnAdd = YAHOO.util.Dom.get("btnAdd");
        txtDomain = YAHOO.util.Dom.get("txtAddDomain");
    }

    var bindEvents = function(){
        YAHOO.util.Event.addListener(btnAdd, "click", addDomain);
        YAHOO.util.Event.addListener(btnCancel, "click", function(){
                panel.hide();
        });
    }

    var renderPanel = function(){
        panel = SM.Panel.createPanel("panelAddDomain");
        panel.setHeader("Add Domain");
        panel.setFooter("close to cancel");

        // make panel visible
        YAHOO.util.Dom.setStyle('panelAddDomain', 'display', 'block');
    }
    
    var init = function(){
        setVars();
        bindEvents();
        renderPanel();
        return panel;
    }

    return{
        init:init,
        addDomainTransaction:addDomainTransaction,
        registerCallback:registerCallback
    }
}();

SM.SettingsPanel = function(){
    var panel;

    var renderPanel = function(config){
        panel = SM.Panel.createPanel("panelSettings", config);
        panel.setHeader("Settings");
        
        // make panel visible
        YAHOO.util.Dom.setStyle('panelSettings', 'display', 'block');
    }

    var init = function(config){
        renderPanel(config);
        return panel;
    }

    return{
        init:init
    }
}();

SM.Paginator = function(){
    var paginator, callbacks=[];
    var defaultConfig = {
        rowsPerPage: 10,
        totalRecords : 15
    }

    var registerCallback = function(fn){
        callbacks.push(fn);
    }

    var executeCallbacks = function(newState){
        for(var i=0; i < callbacks.length; i++){
            if(YAHOO.lang.isFunction(callbacks[i])){
                callbacks[i](newState);
            }
        }
    }

    var MyApp = {
        handlePagination : function (newState) {
            // Collect page data using the requested page number
            //var pageContent = MyApp.getContent(newState.page);

            // Update the content area
            //MyApp.replaceContent(pageContent);

            // Update the Paginator's state
            paginator.setState(newState);
            executeCallbacks(newState);
        }
    };

    var initPaginator = function(id, config){
        paginator = new YAHOO.widget.Paginator();
        paginator.set('rowsPerPage', config.rowsPerPage);
        paginator.set('totalRecords', config.totalRecords);
        paginator.set('containers', id);
        paginator.subscribe('changeRequest',MyApp.handlePagination);
    }

    var init = function(id, config){
        if(!config){
            config = defaultConfig;
        }

        initPaginator(id, config);
        return paginator;
    }

    return {
        init:init,
        registerCallback:registerCallback
    }
}();


SM.CP = function(){
    var chkConfigs = [], addDomainPanel, btnAddDomain, selDomains, btnViewReport, domain_name, errorCheckBoxes=[],
    sm_messages, btnClearMessages, btnViewSettings, selStatsDateRange, initialLoad=true, urlStats, timestamp;
    var settingsPanel;
    var currentPage=1, rowsPerPage=5, paginator=null, selRowsPerPage;
    var sReport = "/index.php/rs/viewReport";
    var sEditMessage = "/index.php/rs/editMessage";

    var addChkConfig = function(config){
        chkConfigs.push(config);
    }

    var createPanel = function(){
        addDomainPanel = SM.AddDomainPanel.init();
        addDomainPanel.render();

        settingsPanel = SM.SettingsPanel.init({width:"600px"});
        settingsPanel.render();
    }

    var createPaginator = function(){
        if(paginator === null){
            paginator = SM.Paginator.init("paginator", {rowsPerPage: rowsPerPage});
            paginator.render();
        }
    }

    var setVars = function(){
        btnAddDomain = YAHOO.util.Dom.get("btnAddDomain");
        selDomains = YAHOO.util.Dom.get("selDomains");
        btnViewReport = YAHOO.util.Dom.get("btnViewReport");
        selRowsPerPage = YAHOO.util.Dom.get("selRowsPerPage");
        btnClearMessages = YAHOO.util.Dom.get("btnClearMessages");
        btnViewSettings = YAHOO.util.Dom.get("btnViewSettings");
        selStatsDateRange = YAHOO.util.Dom.get("selStatsDateRange");
        urlStats = YAHOO.util.Dom.get("urlStats");
        resetTimestamp();

        // this loop puts all the error check box elements in a single array (view errors, view warnings, etc...)
        for(var i=0; i < chkConfigs.length; i++){
            var el = YAHOO.util.Dom.get(chkConfigs[i].id);
            errorCheckBoxes.push(el);
        }
    }

    var resetTimestamp = function(){
        timestamp = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000); // timestamp is used to freeze the state of queried message records
    }

    var addSelectOptions = function(results){
        for(var i=0; i < results.feedback.length; i++){
            selDomains.options[i]=new Option(results.feedback[i].domain_name, results.feedback[i].id, false, false)
        }
    }

    var clearSelectOptions = function(){
        selDomains.length = 0;
    }

    var displayReport = function(result){
        var el = YAHOO.util.Dom.get("maincontent");
        el.innerHTML = result.report;

        btnClearMessages.disabled = false;
        //executeDisplayReportCallbacks();
    }

    var viewReportTransaction = function(result){
        displayReport(result);
        paginator.set('totalRecords', result.total);
        sm_messages = YAHOO.util.Dom.getElementsByClassName("sm_message");
        YAHOO.util.Event.addListener(sm_messages, "click", handleMessageClick);

        if(initialLoad){ // initial load represents the first time the page is loaded (true)
            //drawChart(result);
        }

        initialLoad = false;
    }

    /*
    var drawChart = function(result){
        var config = [
           {type: "errors", count: result.total_error},
           {type: "warnings", count: result.total_warning},
           {type: "strict", count: result.total_strict},
           {type: "notice", count: result.total_notice}
        ];
        SM.Chart.init(config);
    }*/

    var getCheckboxArgs = function(){
        var args=[], qstring;
        YAHOO.log("errorCheckBoxes: " + YAHOO.lang.dump(errorCheckBoxes));
        for(var i=0; i < errorCheckBoxes.length; i++){
            if(errorCheckBoxes[i].checked){
                YAHOO.log("i checked: " + i);
                args.push(errorCheckBoxes[i].id);
            }
        }

        if(args.length > 0){
            qstring = args.join(",");
            return qstring;
        }else{
            return false;
        }
    }

    var initViewport = function(){
        var postQueryString = "timestamp=" + timestamp + "&domain_name=" + domain_name + "&page=" + currentPage + "&rowsPerPage=" + rowsPerPage;

        // get checkboxes
        var checkBoxArgs = getCheckboxArgs();
        if(checkBoxArgs){
            postQueryString = postQueryString + "&id=" + checkBoxArgs;
        }

        SM.Transaction.registerCallback(viewReportTransaction);
        SM.Transaction.doPost(sReport, postQueryString);
    }

    var viewReport = function(event){
        // get selected domain id
        for(var i=0; i < selDomains.length; i++){
            if(selDomains.options[i].selected){
                domain_name = selDomains.options[i].text;
                break;
            }
        }

        currentPage = 1; // reset page to 1
        paginator.setPage(1, true);
        resetTimestamp();
        initViewport();
    }

    var handleRowsPerPageChange = function(event){
        var target = YAHOO.util.Event.getTarget(event);
        rowsPerPage = target.value;
        paginator.set('rowsPerPage', rowsPerPage);
        initViewport();
    }

    var handleMessageClick = function(event){
        var target = YAHOO.util.Event.getTarget(event);

        if(target.className == "messageDelete"){
            if(confirm("Are you sure you want to delete this message?")){

                var postQueryString = "action=delete&message_id=" + this.id + "&domain_name=" + domain_name + "&page=" + currentPage + "&rowsPerPage=" + rowsPerPage;

                // get checkboxes
                var checkBoxArgs = getCheckboxArgs();
                if(checkBoxArgs){
                    postQueryString = postQueryString + "&checkbox_id=" + checkBoxArgs + "&timestamp=" + timestamp;
                }

                SM.Transaction.registerCallback(viewReportTransaction);
                SM.Transaction.doPost(sEditMessage, postQueryString);
            }
        }else if(target.className == "expand"){
            YAHOO.util.Dom.setStyle(this, "height", "auto");
            YAHOO.util.Dom.removeClass(target, "expand");
            YAHOO.util.Dom.addClass(target, "collapse");
            target.innerHTML = "[-]";
        }else if(target.className == "collapse"){
            YAHOO.util.Dom.setStyle(this, "height", "11px");
            YAHOO.util.Dom.removeClass(target, "collapse");
            YAHOO.util.Dom.addClass(target, "expand");
            target.innerHTML = "[+]";
        }
    }

    var handleClearAllMessages = function(event){
        if(confirm("Are you sure you want to clear all messages for " + domain_name + "?")){
            var postQueryString = "action=clear&domain_name=" + domain_name;

            SM.Transaction.registerCallback(viewReportTransaction);
            SM.Transaction.doPost(sEditMessage, postQueryString);
        }
    }

    var handleViewSettingsClick = function(event){
        settingsPanel.show();
    }

    var changeStatsRangeTransaction = function(result){
        //drawChart(result);
        urlStats.innerHTML = result.urls;
    }

    var handleStatsRangeChange = function(event){
        var target = YAHOO.util.Event.getTarget(event);
        var sUrl = "/index.php/rs/viewStats";
        var postQueryString = "domain_name=" + domain_name + "&range=" + target.value;

        SM.Transaction.registerCallback(changeStatsRangeTransaction);
        SM.Transaction.doPost(sUrl, postQueryString);
    }

    var bindEvents = function(){
        YAHOO.util.Event.addListener(btnAddDomain, "click", function(event){addDomainPanel.show();});
        YAHOO.util.Event.addListener(btnViewReport, "click", viewReport);
        YAHOO.util.Event.addListener(selRowsPerPage, "change", handleRowsPerPageChange);
        YAHOO.util.Event.addListener(btnClearMessages, "click", handleClearAllMessages);
        YAHOO.util.Event.addListener(btnViewSettings, "click", handleViewSettingsClick);
        YAHOO.util.Event.addListener(selStatsDateRange, "change", handleStatsRangeChange);

        YAHOO.util.Event.addListener(errorCheckBoxes, "click", function(event){
            currentPage = 1;
            paginator.setPage(1, true);
            initViewport();
        });
    }

    var init = function(){
        setVars();
        bindEvents();
        createPanel();
        createPaginator();
    }

    var handlePagination = function(newState){
        // update viewport
        currentPage = paginator.getCurrentPage();
        initViewport();
    }

    return{
        init:init,
        addChkConfig:addChkConfig,
        clearSelectOptions:clearSelectOptions,
        addSelectOptions:addSelectOptions,
        handlePagination:handlePagination
    }
	
}();
SM.YUILoader.registerCallback(SM.CP.init);
SM.AddDomainPanel.registerCallback(SM.CP.clearSelectOptions);
SM.AddDomainPanel.registerCallback(SM.CP.addSelectOptions);
SM.Paginator.registerCallback(SM.CP.handlePagination);

/*
SM.Chart = function(){
    var example=[];
    
    var init = function(config){
        // TODO: this line executes every time init() is run; changes this so it only runs once.
        YAHOO.widget.Chart.SWFURL = "http://yui.yahooapis.com/2.8.0r4/build/charts/assets/charts.swf";
        
        var myDataSource = new YAHOO.util.DataSource(config);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource.responseSchema = {
            fields: [ "type","count"]
        };

        var seriesDef = [
            {
                style: {
                    colors: [0xFCCCA2,0xFEFDC6,0xB2EDC7,0xC2E3FD]
                }
            }
        ];


        var myChart = new YAHOO.widget.PieChart("chart", myDataSource, {
            style:{
                legend:{
                    display: "bottom"
                }
            },
            dataField: "count",
            categoryField: "type",
            series: seriesDef
        });

        
    }

    return {
        init:init
    }
}();
SM.YUILoader.registerCallback(SM.Chart.init);
*/